using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Threading;
using System.IO;
namespace HTML2TEXT
{
	/// <summary>
	/// Summary description for Form1.
	/// </summary>
	public class FormMain : System.Windows.Forms.Form
	{
		private System.Windows.Forms.Button btnSelectFile;
		private System.Windows.Forms.Label lbStatus;
		private System.Windows.Forms.OpenFileDialog openFileDialog1;
		string stFileName ;
		/// <summary>
		/// Required designer variable.
		/// </summary>
		private System.ComponentModel.Container components = null;

		public FormMain()
		{
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();

			//
			// TODO: Add any constructor code after InitializeComponent call
			//
		}

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if (components != null) 
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.btnSelectFile = new System.Windows.Forms.Button();
			this.lbStatus = new System.Windows.Forms.Label();
			this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
			this.SuspendLayout();
			// 
			// btnSelectFile
			// 
			this.btnSelectFile.Location = new System.Drawing.Point(136, 16);
			this.btnSelectFile.Name = "btnSelectFile";
			this.btnSelectFile.Size = new System.Drawing.Size(96, 23);
			this.btnSelectFile.TabIndex = 0;
			this.btnSelectFile.Text = "&Select File";
			this.btnSelectFile.Click += new System.EventHandler(this.btnSelectFile_Click);
			// 
			// lbStatus
			// 
			this.lbStatus.Location = new System.Drawing.Point(16, 64);
			this.lbStatus.Name = "lbStatus";
			this.lbStatus.Size = new System.Drawing.Size(328, 64);
			this.lbStatus.TabIndex = 1;
			this.lbStatus.Text = "Select files to convert.";
			// 
			// FormMain
			// 
			this.AutoScaleBaseSize = new System.Drawing.Size(7, 17);
			this.ClientSize = new System.Drawing.Size(352, 134);
			this.Controls.Add(this.lbStatus);
			this.Controls.Add(this.btnSelectFile);
			this.Font = new System.Drawing.Font("Tahoma", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
			this.MaximizeBox = false;
			this.MinimizeBox = false;
			this.Name = "FormMain";
			this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
			this.Text = "HTML to Plain Text Converter v.1.0";
			this.Load += new System.EventHandler(this.FormMain_Load);
			this.ResumeLayout(false);

		}
		#endregion

		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main() 
		{
			Application.Run(new FormMain());
		}

		private void btnSelectFile_Click(object sender, System.EventArgs e)
		{
			openFileDialog1.Multiselect = true;
			openFileDialog1.Filter = "HTML files (*.html)|*.html|HTM files (*.htm)|*.htm|All files (*.*)|*.*";
			openFileDialog1.RestoreDirectory = true;
			if(openFileDialog1.ShowDialog() == DialogResult.OK)
			{
				System.Threading.Thread thrConvert = new Thread(new ThreadStart(Convert));
				thrConvert.Start();
				
				
			}
			
			
		}

	
		private void Convert()
		{
			foreach(string stFile in openFileDialog1.FileNames)
			{
				stFileName = stFile;
				lbStatus.Text = "Converting " + stFileName;
				try
				{
					StreamReader sr = new StreamReader(stFileName);
					string stContent = sr.ReadToEnd();
					sr.Close();
					stContent = StripHTML(stContent);
					StreamWriter sw = new StreamWriter(stFileName + ".txt");
					sw.Write(stContent);
					sw.Close();
					
				}
				catch(Exception ex)
				{
					MessageBox.Show(this, ex.Message ,"Error : " + stFileName, MessageBoxButtons.OK, MessageBoxIcon.Error);
				}
								
			}
			lbStatus.Text = "Complete successfully.";
			MessageBox.Show("Finished");
			lbStatus.Text = "Select files to convert";
			
						
		}

		private string StripHTML(string source)
		{
    
			try
			{

				string result;

				// Remove HTML Development formatting
				// Replace line breaks with space
				// because browsers inserts space
				result = source.Replace("\r\n", "\n");
				result = source.Replace("\r", " ");
				// Replace line breaks with space
				// because browsers inserts space
				result = result.Replace("\n", " ");
				// Remove step-formatting
				result = result.Replace("\t", string.Empty);
				// Remove repeating speces becuase browsers ignore them
				result = System.Text.RegularExpressions.Regex.Replace(result, 
					@"( )+", " ");
				// Explain
				result = System.Text.RegularExpressions.Regex.Replace(result, 
					@"(<!--)(.)+?(-->)",string.Empty, 
					System.Text.RegularExpressions.RegexOptions.IgnoreCase);

				// Remove the header (prepare first by clearing attributes)
				result = System.Text.RegularExpressions.Regex.Replace(result, 
					@"<( )*head([^>])*>","<head>", 
					System.Text.RegularExpressions.RegexOptions.IgnoreCase);
				result = System.Text.RegularExpressions.Regex.Replace(result, 
					@"(<( )*(/)( )*head( )*>)","</head>", 
					System.Text.RegularExpressions.RegexOptions.IgnoreCase);
				result = System.Text.RegularExpressions.Regex.Replace(result, 
					"(<head>)(.)+?(</head>)",string.Empty, 
					System.Text.RegularExpressions.RegexOptions.IgnoreCase);

				// remove all scripts (prepare first by clearing attributes)
				result = System.Text.RegularExpressions.Regex.Replace(result, 
					@"<( )*script([^>])*>","<script>", 
					System.Text.RegularExpressions.RegexOptions.IgnoreCase);
				result = System.Text.RegularExpressions.Regex.Replace(result, 
					@"(<( )*(/)( )*script( )*>)","</script>", 
					System.Text.RegularExpressions.RegexOptions.IgnoreCase);
				//	result = System.Text.RegularExpressions.Regex.Replace(result, 
				//	         @"(<script>)([^(<script>\.</script>)])*(</script>)",
				//	         string.Empty, 
				//	         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
				result = System.Text.RegularExpressions.Regex.Replace(result, 
					@"(<script>)(.)+?(</script>)",string.Empty, 
					System.Text.RegularExpressions.RegexOptions.IgnoreCase);
        
				// remove all styles (prepare first by clearing attributes)
				result = System.Text.RegularExpressions.Regex.Replace(result, 
					@"<( )*style([^>])*>","<style>", 
					System.Text.RegularExpressions.RegexOptions.IgnoreCase);
				result = System.Text.RegularExpressions.Regex.Replace(result, 
					@"(<( )*(/)( )*style( )*>)","</style>", 
					System.Text.RegularExpressions.RegexOptions.IgnoreCase);
				result = System.Text.RegularExpressions.Regex.Replace(result, 
					"(<style>)(.)+?(</style>)",string.Empty, 
					System.Text.RegularExpressions.RegexOptions.IgnoreCase);

				// insert tabs in spaces of <td> tags
				result = System.Text.RegularExpressions.Regex.Replace(result, 
					@"<( )*td([^>])*>"," ", 
					System.Text.RegularExpressions.RegexOptions.IgnoreCase);

				// insert line breaks in places of <BR> and <LI> tags
				result = System.Text.RegularExpressions.Regex.Replace(result, 
					@"<( )*br( )*>","\r", 
					System.Text.RegularExpressions.RegexOptions.IgnoreCase);
				result = System.Text.RegularExpressions.Regex.Replace(result, 
					@"<( )*li( )*>","\r", 
					System.Text.RegularExpressions.RegexOptions.IgnoreCase);

				// insert line paragraphs (double line breaks) in place
				// if <P>, <DIV> and <TR> tags
				result = System.Text.RegularExpressions.Regex.Replace(result, 
					@"<( )*div([^>])*>","\r", 
					System.Text.RegularExpressions.RegexOptions.IgnoreCase);
				result = System.Text.RegularExpressions.Regex.Replace(result, 
					@"<( )*tr([^>])*>","\r", 
					System.Text.RegularExpressions.RegexOptions.IgnoreCase);
				result = System.Text.RegularExpressions.Regex.Replace(result, 
					@"<( )*p( )+([^>])*>","\r", 
					System.Text.RegularExpressions.RegexOptions.IgnoreCase);

				// Remove remaining tags like <a>, links, images,
				// comments etc - anything thats enclosed inside < >
				result = System.Text.RegularExpressions.Regex.Replace(result, 
					@"<[^>]*>",string.Empty, 
					System.Text.RegularExpressions.RegexOptions.IgnoreCase);

				// replace special characters:
				result = System.Text.RegularExpressions.Regex.Replace(result, 
					@"&nbsp;"," ", 
					System.Text.RegularExpressions.RegexOptions.IgnoreCase);
        
				result = System.Text.RegularExpressions.Regex.Replace(result, 
					@"&bull;"," * ", 
					System.Text.RegularExpressions.RegexOptions.IgnoreCase);    
				result = System.Text.RegularExpressions.Regex.Replace(result, 
					@"&lsaquo;","<", 
					System.Text.RegularExpressions.RegexOptions.IgnoreCase);        
				result = System.Text.RegularExpressions.Regex.Replace(result, 
					@"&rsaquo;",">", 
					System.Text.RegularExpressions.RegexOptions.IgnoreCase);        
				result = System.Text.RegularExpressions.Regex.Replace(result, 
					@"&trade;","(tm)", 
					System.Text.RegularExpressions.RegexOptions.IgnoreCase);        
				result = System.Text.RegularExpressions.Regex.Replace(result, 
					@"&frasl;","/", 
					System.Text.RegularExpressions.RegexOptions.IgnoreCase);        
				result = System.Text.RegularExpressions.Regex.Replace(result, 
					@"&lt;","<", 
					System.Text.RegularExpressions.RegexOptions.IgnoreCase);        
				result = System.Text.RegularExpressions.Regex.Replace(result, 
					@"&gt;",">", 
					System.Text.RegularExpressions.RegexOptions.IgnoreCase);        
				result = System.Text.RegularExpressions.Regex.Replace(result, 
					@"&copy;","(c)", 
					System.Text.RegularExpressions.RegexOptions.IgnoreCase);        
				result = System.Text.RegularExpressions.Regex.Replace(result, 
					@"&reg;","(r)", 
					System.Text.RegularExpressions.RegexOptions.IgnoreCase);    
				// Remove all others. More can be added, see
				result = System.Text.RegularExpressions.Regex.Replace(result, 
					@"&(.{2,6});", string.Empty, 
					System.Text.RegularExpressions.RegexOptions.IgnoreCase);    

				// for testng
				//System.Text.RegularExpressions.Regex.Replace(result, 
				//       this.txtRegex.Text,string.Empty, 
				//       System.Text.RegularExpressions.RegexOptions.IgnoreCase);

				// make line breaking consistent
				result = result.Replace("\n", "\r");

				// Remove extra line breaks and tabs:
				// replace over 2 breaks with 2 and over 4 tabs with 4. 
				// Prepare first to remove any whitespaces inbetween
				// the escaped characters and remove redundant tabs inbetween linebreaks
				/*	result = System.Text.RegularExpressions.Regex.Replace(result, 
						"(\r)( )+(\r)","\r\r", 
						System.Text.RegularExpressions.RegexOptions.IgnoreCase);
					result = System.Text.RegularExpressions.Regex.Replace(result, 
						"( )( )+( )","  ", 
						System.Text.RegularExpressions.RegexOptions.IgnoreCase);
					result = System.Text.RegularExpressions.Regex.Replace(result, 
						"( )( )+(\r)"," \r", 
						System.Text.RegularExpressions.RegexOptions.IgnoreCase);
					result = System.Text.RegularExpressions.Regex.Replace(result, 
						"(\r)( )+( )","\r ", 
						System.Text.RegularExpressions.RegexOptions.IgnoreCase);
					// Remove redundant tabs
					result = System.Text.RegularExpressions.Regex.Replace(result, 
						"(\r)( )+(\r)","\r\r", 
						System.Text.RegularExpressions.RegexOptions.IgnoreCase);
					// Remove multible tabs followind a linebreak with just one tab
					result = System.Text.RegularExpressions.Regex.Replace(result, 
						"(\r)( )+","\r ", 
						System.Text.RegularExpressions.RegexOptions.IgnoreCase);
					// Initial replacement target string for linebreaks
					string breaks = "\r\r\r";
					// Initial replacement target string for tabs
					string tabs = "     ";
					for (int index=0; index<result.Length; index++)
					{
						result = result.Replace(breaks, "\r\r");
						result = result.Replace(tabs, "    ");
						breaks = breaks + "\r";    
						tabs = tabs + " ";
					}

					// Thats it.
				*/
				result = result.Replace("``", "\"");
				result = System.Text.RegularExpressions.Regex.Replace(result, 
						@"(\r)+( )+", "\r");
				result = System.Text.RegularExpressions.Regex.Replace(result, 
					@"( )+", " ");
				result = System.Text.RegularExpressions.Regex.Replace(result, 
					@"(\r)+", "\r");
				
				
				result = result.Trim();
				//	result = result.Replace("\r ","\r");
				//	result = result.Replace("\r","\r\n");
				result = result.Replace("\r","\r\n");

				return result;

			}
			catch(Exception e)
			{
				MessageBox.Show(e.Message, "Error");
				return source;
			}
		}

		private void FormMain_Load(object sender, System.EventArgs e)
		{
		
		}

	}
}
